package com.atguigu.yygh.user.service.impl;


import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author Dufeifei
 * @since 2024-06-23
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        //获取手机号验证码
        String code = loginVo.getCode();
        String phone = loginVo.getPhone();

        //非空验证

        if(StringUtils.isEmpty(code)||StringUtils.isEmpty(phone)){


            throw new YyghException(20001,"请输入账号验证码");
        }
        //到redis 中查询是否一致
        Object o = redisTemplate.opsForValue().get(phone);
        //此处没走redis
        if (code.equals(o)){
            throw new YyghException(20001,"验证码错误");
        }

        //判断手机号是否被注册
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("phone",phone);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);

        if (userInfo==null){
            //未注册
            userInfo = new UserInfo();
            userInfo.setPhone(phone);
            userInfo.setStatus(1);
            baseMapper.insert(userInfo);
        }else if(userInfo.getStatus()==0){
            throw new YyghException(20001,"账户已禁用");
        }

        //返回

        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)){
            name=userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)){
            name=userInfo.getPhone();
        }

        Map<String, Object> map = new HashMap<>();
        map.put("name",name);
        map.put("token", JwtHelper.createToken(userInfo.getId(),name));

        return map;

    }
}
